package com.buzz.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.buzz.fonts.FuturaTextView;
import com.buzz.fonts.MinionTextView;
import com.buzz.layout.BidirSlidingLayout;
import com.buzz.layout.CustomDialog;
import com.buzz.layout.CustomProgressDialog;
import com.buzz.models.Mp3Info;
import com.buzz.models.extag;
import com.buzz.receiver.HeadSetUtil;
import com.buzz.service.BackgroundService;
import com.buzz.utils.GlobalConst;
import com.buzz.models.favorite;
import com.buzz.models.download;
import com.buzz.models.action;
import com.buzz.models.beacon;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.animation.ObjectAnimator;


/**
 * Created by buzz on 2015/5/5.
 */
public class ExhibitionActivity extends Activity {
    final static String TAG = ExhibitionActivity.class.getSimpleName();
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    public static final String STOP_MUSIC = "com.buzz.MusicPlay.STOP_MUSIC";
    public static final String PLAY_MUSIC = "com.buzz.MusicPlay.PLAY_MUSIC";
    public static final String START_MUSIC = "com.buzz.MusicPlay.START_MUSIC";
    public static final String PAUSE_MUSIC = "com.buzz.MusicPlay.PAUSE_MUSIC";
    public static final String BACKGROUND = "com.buzz.background";
    MyApplication myApp;
    ProgressBar progressBar;
    ProgressBar progressBarInit;
    int fileCounter = 0;
    Map<String, MyTask> taskList;
    FuturaTextView title;
    MinionTextView desc;
    RelativeLayout background;
    List<extag> extagList;
    Runnable runnable;
    Handler handler;
    long firstTime = 0;
    Dialog paintDlg;
    boolean canSwipe = false;
    boolean initDone = false;
    MediaPlayer mediaPlayer;
    favorite f;
    favorite delFav;
    download d;
    download delDown;
    Button btnFavor;
    Button btnDownload;
    Button btnIconDownload;
    private Button btnSetting;
    String lvMode = "f";
    //ProgressDialog mProgressDialog;
    CustomProgressDialog mProgressDialog;
    CustomDialog customDialog;
    BidirSlidingLayout bidirSldingLayout;
    ListView listView;
    GestureDetector detector;
    BackgroundServiceReceiver backgroundServiceReceiver;
    IntentFilter intentFilter;
    download subDownload;
    HeadsetPlugReceiver headsetPlugReceiver;
    StopMediaReceiver stopMediaReceiver;
    private static Button btnAudio;
    public static boolean isStopMusic = true;//是否已暂停

    private static Mp3Info mp3Info = new Mp3Info();
    private static MusicPlayService musicPlayService = new MusicPlayService();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exhibition);
        My_Receiver();
        myApp = (MyApplication) getApplication();
        myApp.currentExTagIndex = -1;
        extagList = new ArrayList<extag>();

        //收藏对话框
        paintDlg = new Dialog(ExhibitionActivity.this, R.style.PopupDialog);
        paintDlg.setCancelable(false);

        //下载进度对话框
        //mProgressDialog = new ProgressDialog(this);
        mProgressDialog = new CustomProgressDialog(this, R.style.CustomDialog);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMessage(getString(R.string.msg_file_downloading));
        //mProgressDialog.setIcon(R.drawable.icon_download);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        detector = new GestureDetector(this, new MyGestureDetector());
        listView = (ListView) findViewById(R.id.right_menu_lv);
        listView.setOnItemLongClickListener(new ItemLongListener());//长按列表
        listView.setOnItemClickListener(new ItemListener());//单击列表

        btnFavor = (Button) findViewById(R.id.right_menu_btn_favor);
        btnDownload = (Button) findViewById(R.id.right_menu_btn_download);
        btnIconDownload = (Button) findViewById(R.id.exhibition_btn_download);

        progressBar = (ProgressBar) findViewById(R.id.exhibition_progress_bar);
        progressBar.setVisibility(View.INVISIBLE);
        taskList = new HashMap<String, MyTask>();

        background = (RelativeLayout) findViewById(R.id.exhibition_background);

        title = (FuturaTextView) findViewById(R.id.exhibition_title);
        desc = (MinionTextView) findViewById(R.id.exhibition_desc);

        //右侧菜单
        bidirSldingLayout = (BidirSlidingLayout) findViewById(R.id.exhibition);
        Button btnMenu = (Button) findViewById(R.id.exhibition_btn_menu);
        btnMenu.setOnClickListener(new Btn_Listener());
        progressBarInit = (ProgressBar) findViewById(R.id.exhibition_progress_bar_init);
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                myApp.initSysParams();
                myApp.initExtagList();
                progressBarInit.setVisibility(View.INVISIBLE);
                if (myApp.extagList.size() > 0) {
                    initDone = true;
                    //如果没有展览数据则下载
                    taskList.clear();
                    for (extag et : myApp.extagList.values()) {
                        if (et.getClientpath() != null) {
                            if (!myApp.fileHelper.isFileExist(et.getClientpath().concat(et.getFilename()))) {
                                if (et.getServerpath() != null) {
                                    taskList.put(et.getServerpath(), new MyTask(et.getClientpath(), et.getFilename()));
                                }
                            }

                        }

                        extagList.add(et);
                    }

                    if (taskList.size() > 0) {
                        initDone = false;
                        progressBar.setVisibility(View.VISIBLE);
                        Toast.makeText(ExhibitionActivity.this, getString(R.string.msg_catalog_loading), Toast.LENGTH_LONG).show();
                    }

                    for (Map.Entry<String, MyTask> entry : taskList.entrySet()) {
                        entry.getValue().execute(entry.getKey());
                    }
                }

                if (initDone) {
                    canSwipe = true;
                    //随机显示一个展览目录
                    if (extagList.size() > 0) {
                        Random rnd = new Random();
                        myApp.currentExTagIndex = rnd.nextInt(extagList.size() - 1);
                        showNextOrPrevEx(1);
                    }

                }
            }
        };

        if (!getIntent().hasExtra("index")) {
            //第一次进入需初始化
            Toast.makeText(ExhibitionActivity.this, getString(R.string.msg_app_initializing), Toast.LENGTH_LONG).show();
            handler.postDelayed(runnable, myApp.initTime * 1000);
        } else {
            //小球返回不需要重新初始化
            progressBarInit.setVisibility(View.INVISIBLE);
            for (extag et : myApp.extagList.values()) {
                extagList.add(et);
            }

            initDone = true;
            canSwipe = true;

            //显示原来展览目录
            if (extagList.size() > 0) {
                myApp.currentExTagIndex = getIntent().getIntExtra("index", 0);
                showNextOrPrevEx(2);
            }
        }
        btnFavor.setOnClickListener(new Btn_Listener());//收藏列表
        btnDownload.setOnClickListener(new Btn_Listener());//下载列表
        //设置则跳转设置界面
        btnSetting = (Button) findViewById(R.id.right_menu_btn_setting);
        btnSetting.setOnClickListener(new Btn_Listener());
        btnFavor.callOnClick();
        registerBackgroundServiceReceiver();
        registerHeadsetPlugReceiver();
        registerStopMediaReceiver();
    }

    public void background(){
        Log.w(TAG,"this is background isStopMusic = "+isStopMusic);

        if (isStopMusic) {
            btnAudio.setBackground(getResources().getDrawable(R.drawable.stop_music));
        } else {
            btnAudio.setBackground(getResources().getDrawable(R.drawable.icon_voice));
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBackgroundServiceReceiver();
        unregisterReceiver(headsetPlugReceiver);
        unregisterStopMediaReceiver();
    }

    private void downloadExFiles(download down, String dlgTitle) {
        taskList.clear();
        fileCounter = 0;
        String[] suffix = new String[]{"_cc.mp3", "_en.mp3", "_sc.mp3", "_pt.mp3"};
        for (action ac : down.getActionList()) {
            if (ac.getClientpath() != null && ac.getServerpath() != null) {
                //音频文件需转换为真实路径和文件名
                if (ac.getContenttype().equals("audio")) {
                    for (String s : suffix) {
                        String realFileName = ac.getFilename().replace(".mp3", s);
                        String realServerPath = ac.getServerpath().replace(".mp3", s);
                        if (!myApp.fileHelper.isFileExist(ac.getClientpath().concat(realFileName))) {
                            taskList.put(realServerPath, new MyTask(ac.getClientpath(), realFileName));
                        }
                    }
                } else {
                    //图片则直接下载
                    if (!myApp.fileHelper.isFileExist(ac.getClientpath().concat(ac.getFilename()))) {
                        taskList.put(ac.getServerpath(), new MyTask(ac.getClientpath(), ac.getFilename()));
                    }
                }
            }
        }

        if (taskList.size() > 0) {
            mProgressDialog.setTitle(dlgTitle);
            mProgressDialog.setProgress(0);
            mProgressDialog.incrementProgressBy(1);
            mProgressDialog.setMax(taskList.size());
            mProgressDialog.show();
        }

        for (Map.Entry<String, MyTask> entry : taskList.entrySet()) {
            entry.getValue().execute(entry.getKey());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        detector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > GlobalConst.SYSTEM_EXIT_INTERVAL) {
                Toast.makeText(ExhibitionActivity.this, getString(R.string.msg_quit_system), Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
                return true;
            } else {
                Intent intent = new Intent(this, BackgroundService.class);
                stopService(intent);
                this.finish();
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showNextOrPrevEx(int flag) {
        if (extagList.size() > 0) {
            if (flag == 1) {
                //向右滑动
                myApp.currentExTagIndex++;
                if (myApp.currentExTagIndex >= extagList.size()) {
                    myApp.currentExTagIndex = 0;
                }
            } else if (flag == 0) {
                //向左滑动
                myApp.currentExTagIndex--;
                if (myApp.currentExTagIndex < 0) {
                    myApp.currentExTagIndex = extagList.size() - 1;
                }
            } else if (flag == 2) {
                //显示原来图片，不添加逻辑
            }

            if (myApp.currentExTagIndex > -1) {
                //显示或隐藏下载图标
                for (download down : myApp.getDownloadList()) {
                    if (down.getDextag().getExtag().equals(extagList.get(myApp.currentExTagIndex).getExtag())) {
                        if (!down.isFinished()) {
                            subDownload = down;
                            btnIconDownload.setVisibility(View.VISIBLE);
                            btnIconDownload.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    lvMode = "d";
                                    downloadExFiles(subDownload, title.getText().toString());
                                }
                            });
                        } else {
                            btnIconDownload.setVisibility(View.INVISIBLE);
                            btnIconDownload.setOnClickListener(null);
                        }

                        break;
                    } else {
                        btnIconDownload.setVisibility(View.INVISIBLE);
                        btnIconDownload.setOnClickListener(null);
                    }
                }
            }

            //选中收藏按钮
            btnFavor.callOnClick();
        }
    }

    private void playAudio(String audioPath) {
        //停止后台音频
        myApp.stopServiceMedia = true;
        /*if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }*/

        try {
            //检查耳机并播放前台音频
            if (myApp.headSetConnected) {
                String suffix = "";
                switch (myApp.logonUser.voiceLang) {
                    case GlobalConst.VOICE_LANG_CC:
                        suffix = "_cc.mp3";
                        break;

                    case GlobalConst.VOICE_LANG_SC:
                        suffix = "_sc.mp3";
                        break;

                    case GlobalConst.VOICE_LANG_EN:
                        suffix = "_en.mp3";
                        break;

                    case GlobalConst.VOICE_LANG_PT:
                        suffix = "_pt.mp3";
                        break;
                }
                mp3Info.setUrl(GlobalConst.PATH_SDCARD.concat(audioPath.replace(".mp3", suffix)));
                if (isStopMusic){
                    Intent intent = new Intent(PLAY_MUSIC);
                    sendBroadcast(intent);
                    isStopMusic = false;
                    background();

                }else {
                    Intent intent = new Intent(STOP_MUSIC);
                    sendBroadcast(intent);
                    isStopMusic = true;
                    background();
                }
                //mediaPlayer.setDataSource(GlobalConst.PATH_SDCARD.concat(audioPath.replace(".mp3", suffix)));
                //mediaPlayer.prepare();
            } else {
                Toast.makeText(ExhibitionActivity.this, getString(R.string.msg_conn_headset), Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void registerStopMediaReceiver() {
        stopMediaReceiver = new StopMediaReceiver();
        intentFilter = new IntentFilter(GlobalConst.ACTION_STOP_MEDIA);
        registerReceiver(stopMediaReceiver, intentFilter);
    }

    private void unregisterStopMediaReceiver() {
        if (stopMediaReceiver != null) {
            unregisterReceiver(stopMediaReceiver);
        }
    }

    private void unregisterBackgroundServiceReceiver() {
        if (backgroundServiceReceiver != null) {
            unregisterReceiver(backgroundServiceReceiver);
        }
    }

    private void registerBackgroundServiceReceiver() {
        backgroundServiceReceiver = new BackgroundServiceReceiver();
        intentFilter = new IntentFilter(GlobalConst.ACTION_MY_APP_SERVICE);
        registerReceiver(backgroundServiceReceiver, intentFilter);
    }

    private class MyTask extends AsyncTask<String, Integer, String> {
        private String clientPath;
        private String fileName;

        protected MyTask(String clientPath, String fileName) {
            this.clientPath = clientPath;
            this.fileName = fileName;
        }

        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            //Log.i(TAG, "onPreExecute() called");
        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected String doInBackground(String... params) {
            //Log.i(TAG, "doInBackground(Params... params) called");
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(params[0]);
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    long total = entity.getContentLength();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024 * 10];
                    int count = 0;
                    int length = -1;
                    while ((length = is.read(buf)) != -1) {
                        baos.write(buf, 0, length);
                        count += length;
                        //调用publishProgress公布进度,最后onProgressUpdate方法将被执行
                        publishProgress((int) ((count / (float) total) * 100));
                        //为了演示进度,休眠500毫秒
                        //Thread.sleep(5);
                    }

                    //保存文件
                    String filePath = GlobalConst.PATH_SDCARD + this.clientPath;
                    String fileName = this.fileName;
                    String saveTo = filePath + fileName;
                    File file = new File(filePath);
                    file.mkdirs();
                    file = null;
                    file = new File(saveTo);
                    file.createNewFile();
                    OutputStream outputStream = new FileOutputStream(file);
                    outputStream.write(baos.toByteArray());
                    baos.close();
                    baos.flush();
                    outputStream.close();
                    outputStream.flush();
                    file = null;

                    return this.fileName;
                }
            } catch (Exception e) {
                //Log.i(TAG, e.getMessage());
            }
            return null;
        }

        //onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            //Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
            if (lvMode.equals("d")) {
            } else {
                progressBar.setProgress(progresses[0]);
            }

        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(String result) {
            fileCounter++;
            if (lvMode.equals("d")) {
                mProgressDialog.setProgress(fileCounter);
            } else {
                progressBar.setSecondaryProgress((int) ((fileCounter * 1.0 / taskList.size()) * 100));
            }

            if (fileCounter == taskList.size()) {
                if (lvMode.equals("d")) {
                    //关闭下载对话框
                    mProgressDialog.setProgress(0);
                    mProgressDialog.dismiss();
                    //刷新下载列表
                    btnDownload.callOnClick();
                    //隐藏下载图标
                    btnIconDownload.setVisibility(View.INVISIBLE);
                } else {
                    progressBar.setVisibility(View.INVISIBLE);
                    Toast.makeText(ExhibitionActivity.this, getString(R.string.msg_catalog_finished), Toast.LENGTH_LONG).show();
                }

                initDone = true;
                canSwipe = !bidirSldingLayout.isRightLayoutVisible();
            }
        }
    }

    public class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (canSwipe) {
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    //right
                    /*
                    ViewHelper.setPivotX(bidirSldingLayout, bidirSldingLayout.getWidth() / 2);
                    ViewHelper.setPivotY(bidirSldingLayout, bidirSldingLayout.getHeight() / 2);
                    ObjectAnimator.ofFloat(bidirSldingLayout, "rotationY", 0, 90).setDuration(1000).start();*/
                    ObjectAnimator.ofFloat(bidirSldingLayout, "translationX", bidirSldingLayout.getWidth(), 0).setDuration(500).start();

                    showNextOrPrevEx(1);

                    //ObjectAnimator.ofFloat(bidirSldingLayout, "rotationY", 90, 0).setDuration(1000).start();

                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    //left
                    /*
                    ViewHelper.setPivotX(bidirSldingLayout, bidirSldingLayout.getWidth() / 2);
                    ViewHelper.setPivotY(bidirSldingLayout, bidirSldingLayout.getHeight() / 2);
                    ObjectAnimator.ofFloat(bidirSldingLayout, "rotationY", 0, -90).setDuration(1000).start();*/
                    ObjectAnimator.ofFloat(bidirSldingLayout, "translationX", -bidirSldingLayout.getWidth(), 0).setDuration(500).start();

                    showNextOrPrevEx(0);

                    //ObjectAnimator.ofFloat(bidirSldingLayout, "rotationY", -90, 0).setDuration(1000).start();

                }
            }

            return true;
        }

        /*
        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
        }*/
    }

    public class BackgroundServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            HashMap<String, Integer> map = (HashMap<String, Integer>) intent.getSerializableExtra("map");
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                //如果检测到某展览Beacon则跳转到小球页面
                for (beacon b : myApp.beaconList.values()) {
                    if (b.getBeaconid().equals(entry.getKey()) && entry.getValue() >= GlobalConst.RANGE_ACCESS_BALL_VIEW
                            && b.getUsage().equals(GlobalConst.BEACON_USAGE_DETAIL)) {

                        //跳转到小球页面
                        Intent it = new Intent();
                        it.setClass(ExhibitionActivity.this, MainActivity.class);
                        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(it);

                        //切换展览索引
                        for (int i = 0; i < extagList.size(); i++) {
                            if (extagList.get(i).getExtag().equals(b.getExtag())) {
                                myApp.currentExTagIndex = i;
                                break;
                            }
                        }

                        //停止播放语音
                        Intent intent1 = new Intent(STOP_MUSIC);
                        sendBroadcast(intent1);
                        isStopMusic = true;
                        ExhibitionActivity.this.finish();
                    }
                }
            }
        }
    }

    public class Btn_Listener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.exhibition_btn_menu://左右菜单切换按钮
                    if (initDone) {
                        if (bidirSldingLayout.isRightLayoutVisible()) {
                            bidirSldingLayout.scrollToContentFromRightMenu();
                            canSwipe = true;
                        } else {
                            bidirSldingLayout.initShowRightState();
                            bidirSldingLayout.scrollToRightMenu();
                            canSwipe = false;
                        }
                    }
                    break;
                case R.id.right_menu_btn_favor://收藏模式
                    lvMode = "f";
                    btnFavor.setBackground(getResources().getDrawable(R.drawable.red_love));
                    btnDownload.setBackground(getResources().getDrawable(R.drawable.icon_download));
                    String sTitle = "";
                    String sDesc = "";
                    if (myApp.currentExTagIndex > -1) {
                        extag targetExtag = extagList.get(myApp.currentExTagIndex);
                        switch (myApp.logonUser.defaultLang) {
                            case GlobalConst.DEFAULT_LANG_EN:
                                sTitle = targetExtag.getTitle_en();
                                sDesc = targetExtag.getDescription_en();
                                break;
                            case GlobalConst.DEFAULT_LANG_CN:
                                sTitle = targetExtag.getTitle_cn();
                                sDesc = targetExtag.getDescription_cn();
                                break;
                            case GlobalConst.DEFAULT_LANG_TW:
                                sTitle = targetExtag.getTitle_tw();
                                sDesc = targetExtag.getDescription_tw();
                                break;
                            case GlobalConst.DEFAULT_LANG_PT:
                                sTitle = targetExtag.getTitle_pt();
                                sDesc = targetExtag.getDescription_pt();
                                break;
                        }
                        title.setText(sTitle);
                        desc.setText(sDesc);
                        background.setBackground(Drawable.createFromPath(GlobalConst.PATH_SDCARD
                                .concat(extagList.get(myApp.currentExTagIndex).getClientpath())
                                .concat(extagList.get(myApp.currentExTagIndex).getFilename())));

                        //更新收藏列表
                        List<favorite> favoriteList = myApp.getFavoriteList();
                        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                        String itemTitle = "";
                        for (favorite f : favoriteList) {
                            if (f.getExtag().equals(targetExtag.getExtag())) {
                                Map<String, Object> map = new HashMap<String, Object>();
                                switch (myApp.logonUser.defaultLang) {
                                    case GlobalConst.DEFAULT_LANG_EN:
                                        itemTitle = f.getTitle_en() + "-" + f.getArtist_en();
                                        break;
                                    case GlobalConst.DEFAULT_LANG_CN:
                                        itemTitle = f.getTitle_cn() + "-" + f.getArtist_cn();
                                        break;
                                    case GlobalConst.DEFAULT_LANG_TW:
                                        itemTitle = f.getTitle_tw() + "-" + f.getArtist_tw();
                                        break;
                                    case GlobalConst.DEFAULT_LANG_PT:
                                        itemTitle = f.getTitle_pt() + "-" + f.getArtist_pt();
                                        break;
                                }
                                map.put("title", itemTitle);
                                map.put("favorite", f);
                                map.put("mode", "f");
                                list.add(map);
                            }
                        }
                        listView.setAdapter(new MyAdspter(getApplicationContext(), list));
                    } else {
                        listView.setAdapter(new MyAdspter(getApplicationContext(), new ArrayList<Map<String, Object>>()));
                    }
                    break;
                case R.id.right_menu_btn_download://下载模式
                    lvMode = "d";
                    //选中
                    btnDownload.setBackground(getResources().getDrawable(R.drawable.red_download));
                    btnFavor.setBackground(getResources().getDrawable(R.drawable.icon_love));
                    //更新下载列表
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    String itemTitle = "";
                    for (download d : myApp.getDownloadList()) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        switch (myApp.logonUser.defaultLang) {
                            case GlobalConst.DEFAULT_LANG_EN:
                                itemTitle = d.getDextag().getTitle_en();
                                break;
                            case GlobalConst.DEFAULT_LANG_CN:
                                itemTitle = d.getDextag().getTitle_cn();
                                break;
                            case GlobalConst.DEFAULT_LANG_TW:
                                itemTitle = d.getDextag().getTitle_tw();
                                break;
                            case GlobalConst.DEFAULT_LANG_PT:
                                itemTitle = d.getDextag().getTitle_pt();
                                break;
                        }
                        map.put("title", itemTitle);
                        map.put("download", d);
                        map.put("mode", "d");
                        list.add(map);
                    }
                    listView.setAdapter(new MyAdspter(getApplicationContext(), list));
                    break;
                case R.id.right_menu_btn_setting:
                    Intent it = new Intent(ExhibitionActivity.this, SettingActivity.class);
                    it.putExtra("root", "ex");
                    startActivity(it);
                    break;
            }
        }
    }
    public class ItemLongListener implements AdapterView.OnItemLongClickListener{
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            MyAdspter myAdspter = (MyAdspter) parent.getAdapter();
            Map<String, Object> map = (Map<String, Object>) myAdspter.getItem(position);
            //下载模式
            if (lvMode.equals("d")) {
                delDown = (download) map.get("download");
                //下载完成才能进行操作
                if (delDown.isFinished()) {
                    CustomDialog.Builder builder = new CustomDialog.Builder(ExhibitionActivity.this);
                    builder.setTitle(getString(R.string.msg_dlg_title_tips));
                    builder.setMessage(getString(R.string.msg_delete_all_files));
                    builder.setConfirmButton(getString(R.string.msg_dlg_ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //删除所有相关文件
                            String[] suffix = new String[]{"_cc.mp3", "_en.mp3", "_sc.mp3", "_pt.mp3"};
                            for (action ac : delDown.getActionList()) {
                                if (ac.getClientpath() != null && ac.getServerpath() != null) {
                                    //音频文件需转换为真实文件后删除
                                    if (ac.getContenttype().equals("audio")) {
                                        for (String s : suffix) {
                                            String realFileName = ac.getFilename().replace(".mp3", s);
                                            myApp.fileHelper.deleteFile(ac.getClientpath().concat(realFileName));
                                        }
                                    } else {
                                        //图片则直接删除
                                        myApp.fileHelper.deleteFile(ac.getClientpath().concat(ac.getFilename()));
                                    }
                                }
                            }

                            //刷新下载列表
                            btnDownload.callOnClick();
                            customDialog.dismiss();
                        }
                    });

                    builder.setBackButton(getString(R.string.msg_dlg_cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            customDialog.dismiss();
                        }
                    });

                    customDialog = builder.create();
                    customDialog.show();
                }
            }
            //收藏模式
            else if (lvMode.equals("f")) {
                delFav = (favorite) map.get("favorite");
                CustomDialog.Builder builder = new CustomDialog.Builder(ExhibitionActivity.this);
                builder.setTitle(getString(R.string.msg_dlg_title_tips));
                builder.setMessage(getString(R.string.msg_delete_favorite));
                builder.setConfirmButton(getString(R.string.msg_dlg_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除收藏
                        myApp.removeFavoriteFromList(delFav.getImagepath());
                        //刷新收藏列表
                        btnFavor.callOnClick();
                        customDialog.dismiss();
                    }
                });

                builder.setBackButton(getString(R.string.msg_dlg_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        customDialog.dismiss();
                    }
                });

                customDialog = builder.create();
                customDialog.show();
            }
            return true;
        }
    }
    public class ItemListener implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MyAdspter myAdspter = (MyAdspter) parent.getAdapter();
            Map<String, Object> map = (Map<String, Object>) myAdspter.getItem(position);
            if (lvMode.equals("d")) {//下载模式
                d = (download) map.get("download");
                if (!d.isFinished()) {
                    Log.w(TAG, "d.isFinished() = " + d.isFinished());
                    downloadExFiles(d, map.get("title").toString());
                }
            } else if (lvMode.equals("f")) { //收藏模式
                //d = (download) map.get("download");
                //Log.w(TAG, "finisshed = " + d.finished);
                Log.w(TAG,"btnIconDownload.getVisibility() = "+btnIconDownload.getVisibility());
                if (!(btnIconDownload.getVisibility() == View.VISIBLE)) {
                f = (favorite) map.get("favorite");
                String title = "";
                String artist = "";
                String imageDesc = "";
                View dlgView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog, null);
                switch (myApp.logonUser.defaultLang) {
                    case GlobalConst.DEFAULT_LANG_CN:
                        title = f.getTitle_cn();
                        artist = f.getArtist_cn();
                        imageDesc = f.getDesc_cn();
                        break;

                    case GlobalConst.DEFAULT_LANG_EN:
                        title = f.getTitle_en();
                        artist = f.getArtist_en();
                        imageDesc = f.getDesc_en();
                        break;

                    case GlobalConst.DEFAULT_LANG_TW:
                        title = f.getTitle_tw();
                        artist = f.getArtist_tw();
                        imageDesc = f.getDesc_tw();
                        break;

                    case GlobalConst.DEFAULT_LANG_PT:
                        title = f.getTitle_pt();
                        artist = f.getArtist_pt();
                        imageDesc = f.getDesc_pt();
                        break;
                }

                LinearLayout linearLayout = (LinearLayout) dlgView.findViewById(R.id.dlg_imgView);
                linearLayout.setBackground(Drawable.createFromPath(GlobalConst.PATH_SDCARD.concat(f.getImagepath())));

                TextView txtTitle = (TextView) dlgView.findViewById(R.id.dlg_txt_title);
                TextView txtYear = (TextView) dlgView.findViewById(R.id.dlg_txt_year);
                TextView txtArtist = (TextView) dlgView.findViewById(R.id.dlg_txt_artist);
                TextView txtDesc = (TextView) dlgView.findViewById(R.id.dlg_txt_desc);
                Button btnFavor = (Button) dlgView.findViewById(R.id.dlg_favorite_btn);
                Button btnMenu = (Button) dlgView.findViewById(R.id.dlg_btn_menu);

                btnFavor.setVisibility(View.INVISIBLE);
                btnMenu.setVisibility(View.INVISIBLE);

                txtDesc.setText(imageDesc);
                txtTitle.setText(title);
                txtArtist.setText(artist);
                txtYear.setText(f.getYear());

                final ImageButton ibtn = (ImageButton) dlgView.findViewById(R.id.dlg_btnBack);//返回按钮
                ibtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        paintDlg.dismiss();
                        //停止播放语音
                        Intent intent = new Intent(STOP_MUSIC);
                        sendBroadcast(intent);
                        isStopMusic = true;

                    }
                });

                btnAudio = (Button) dlgView.findViewById(R.id.dlg_audio_btn);//播放按钮
                btnAudio.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //播放音频
                        playAudio(f.getAudiopath());
                    }
                });

                paintDlg.setContentView(dlgView);
                paintDlg.show();
            }else {
                    Toast.makeText(ExhibitionActivity.this,getString(R.string.Download_Resources),Toast.LENGTH_LONG).show();
                }
        }
        }
    }
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            Log.w(TAG, "this is MyReciver");
            String action = intent.getAction();
            if (action.equals(BACKGROUND)) {
                background();
            }
        }
    }
    private void My_Receiver(){
        MyReceiver myReceiver = new MyReceiver();
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction(BACKGROUND);
        registerReceiver(myReceiver,intentFilter1);
    }
    private void registerHeadsetPlugReceiver() {
        headsetPlugReceiver = new HeadsetPlugReceiver();
        IntentFilter filter = new IntentFilter(GlobalConst.ACTION_HEADSET_PLUG);
        registerReceiver(headsetPlugReceiver, filter);
    }

    /*如果拔出耳塞就暂停播放*/
    public class HeadsetPlugReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            if (intent.hasExtra("state")) {
                if (intent.getIntExtra("state", 0) == 0) {
                    Log.i(TAG, "headset not connected");
                    myApp.headSetConnected = false;
                    Intent intent1 = new Intent(STOP_MUSIC);
                    sendBroadcast(intent1);
                    //btnAudio.setBackground(getResources().getDrawable(R.drawable.icon_voice));
                    isStopMusic = true;
                    background();
                } else if (intent.getIntExtra("state", 0) == 1) {
                    Log.i(TAG, "headset connected");
                    myApp.headSetConnected = true;
                }
            }
        }

    }

    /*耳机线控暂停播放*/
    public class StopMediaReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            myApp.stopServiceMedia = true;
            Intent intent1 = new Intent(STOP_MUSIC);
            sendBroadcast(intent1);
            //btnAudio.setBackground(getResources().getDrawable(R.drawable.icon_voice));
            isStopMusic = true;
            background();
        }
    }
}
